package com.thinkgem.jeesite.modules.sys.web;

import cn.jiguang.common.ClientConfig;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.Jpush.JPushClient;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.*;
import com.thinkgem.jeesite.modules.sys.utils.Configuration;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by jyy on 2016/10/19 0019.
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/shoppingOrderProduct")
public class TbShoppingOrderController extends BaseController {

    @Autowired
    private TbShoppingOrderService tbShoppingOrderService;
    @Autowired
    private TbOrderProductService tbOrderProductService;
    @Autowired
    private UserService userService;
    @Autowired
    private TbShopService tbShopService;
    @Autowired
    private TbSenderService tbSenderService;
    @Autowired
    private TbProductService tbProductService;
    @Autowired
    private TbCategoryService tbCategoryService;
    @Autowired
    private TbShopProductService tbShopProductService;


    // 购物订单管理明细展示
    @RequestMapping(value = "reserveShoppingProduct")
    public String reserveProduct(TbOrder tbOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
        String uid = UserUtils.getUser().getId();
        tbOrder.setUid(uid);
        Page<TbOrder> reservePage =  tbShoppingOrderService.findReserveByPage(new Page<TbOrder>(request, response), tbOrder);
        model.addAttribute("reservePage", reservePage);
        return "modules/sys/reserveShoppingProductList";
    }

    // 用户订单查询
    @RequestMapping(value = "showShoppingOrder/{channel}")
    public String queryGardenStuff(TbOrder tbOrder,@PathVariable("channel") Integer channel, TbShop tbShop, HttpServletRequest request, HttpServletResponse response, Model model) {
        String uid = UserUtils.getUser().getId();
        tbShop.setUid(uid);
        tbShop = tbShopService.selectShop(tbShop);
        tbOrder.setShopId(tbShop.getId());
        tbOrder.setChannelId(channel);
        Page<TbOrder> userGardenStuffPage =  tbShoppingOrderService.findUserReserveByPage(new Page<TbOrder>(request, response), tbOrder);
        if(channel==4){
            model.addAttribute("bianli","1");
        }
        model.addAttribute("userGardenStuffPage", userGardenStuffPage);
        if(userGardenStuffPage.getList().size()==0){
           model.addAttribute("message1","无查询结果");
        }
        model.addAttribute("channel", channel);
        return "modules/sys/showShoppingOrderList";
    }

    // 购物预定订单信息
   @RequestMapping(value = "reserveUserShoppingOrderU/{orderId}")
    public String queryReserveGardenStuff(@PathVariable("orderId") Integer orderId, Model model) {
        TbOrder reserveTbOrder =  tbShoppingOrderService.queryOrder(orderId);
       if(reserveTbOrder.getChannelId()==2){
           model.addAttribute("oversea","1");
       }
       User user =UserUtils.getUser();
       TbShop shop = tbShopService.selectByUidAndStatus(user.getId());
        model.addAttribute("reserveTbOrder", reserveTbOrder);
        List<TbOrderProduct> reserveTbOrderProductList =  tbOrderProductService.queryTbOrderProducts(orderId);
        model.addAttribute("reserveTbOrderProductList", reserveTbOrderProductList);
        model.addAttribute("id", orderId);
       model.addAttribute("shop",shop);
        return "modules/sys/reserveUserShoppingOrderQuery";
    }
    // 购物订单信息状态修改前的查询操作
    @RequestMapping(value = "editUserShoppingOrderU/{orderId}")
    public String pupeditReserveGardenStuff(@PathVariable("orderId") Integer orderId, Model model) {
        TbOrder reserveTbOrder =  tbShoppingOrderService.queryOrder(orderId);
        if(reserveTbOrder.getChannelId()==2){
            model.addAttribute("oversea","1");
        }
        model.addAttribute("tbOrder", reserveTbOrder);
        List<TbOrderProduct> reserveTbOrderProductList =  tbOrderProductService.queryTbOrderProducts(orderId);
        model.addAttribute("editTbOrderProductList", reserveTbOrderProductList);
        model.addAttribute("endlen",reserveTbOrderProductList.size());
        return "modules/sys/editShoppingOrderState";
    }
    // 购物订单状态的修改
    @RequestMapping(value = "editUserShoppingState")
    public String editReserveGardenStuff(String id,String state,String logisticsNumber,String arriveTime,String logisticsCode,Model model) {
        Map map=new HashMap();
        map.put("state",state);
        map.put("id",id);
        map.put("logisticsNumber",logisticsNumber);
        map.put("logisticsCode",logisticsCode);
        if(state!=null){
            if(StringUtils.isNotBlank(state+"")&&state!=null){
                if(Global.isDemoMode()){
                    model.addAttribute("message", "演示模式，不允许操作！");
                    return "modules/sys/editShoppingOrderState";
                }
                try{
                    tbShoppingOrderService.editOrderState(map);
                    model.addAttribute("message", "修改订单状态成功");
                }catch (Exception e){
                    model.addAttribute("message", "修改订单状态失败");
                }
            }
        }
        int orderId=Integer.parseInt(id);
        TbOrder reserveTbOrder =  tbShoppingOrderService.queryOrder(orderId);
        model.addAttribute("tbOrder", reserveTbOrder);
        model.addAttribute("logisticsNumber", logisticsNumber);
        List<TbOrderProduct> reserveTbOrderProductList =  tbOrderProductService.queryTbOrderProducts(orderId);
        //如果是便利生活的商品，店铺发货后要减库存
      /*  if(!CollectionUtils.isEmpty(reserveTbOrderProductList)){
            for(int i=0;i<reserveTbOrderProductList.size();i++){
                TbProduct tbProduct = tbProductService.selectByPrimaryKey(reserveTbOrderProductList.get(i).getProductId());
                TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
                String categoryId = tbCategory.getParentIds().substring(4,5);
                if(null!=categoryId&&!"".equals(categoryId)&&"4".equals(categoryId)){//3是生活预定4，是便利生活
                   // tbShoppingOrderService.subStoreNum(reserveTbOrderProductList.get(i));
                    //根据商品id得到tb_shop_product中的商品库存数量和库存预警值，如果库存小于预警值，向系统消息中插入一条数据
                    TbShopProduct tbShopProduct=tbShopProductService.get(reserveTbOrderProductList.get(i).getShopProductId()+"");
                    if(tbShopProduct!=null&&null!=tbShopProduct.getAlertStoreNum()&&tbShopProduct.getAlertStoreNum()>tbShopProduct.getStoreNum()){
                       TbMsgNotify tbMsgNotify=new TbMsgNotify();
                        tbMsgNotify.setUid(UserUtils.getUser().getId());
                        tbMsgNotify.setTitle("库存不足提醒");
                        tbMsgNotify.setContent(tbProduct.getTitle()+"的数量低于预警值，请及时补充！");
                        tbMsgNotify.setStatus("0");
                        Date da=new Date();
                        tbMsgNotify.setCreateTime(da);
                        tbMsgNotify.setUpdateTime(da);
                        tbMsgNotifyService.insertMsg(tbMsgNotify);
                    }

                }

            }
        }*/
        model.addAttribute("editTbOrderProductList", reserveTbOrderProductList);
        model.addAttribute("endlen",reserveTbOrderProductList.size());
        TbOrder tb=new TbOrder();
        tb.setOrderNo(reserveTbOrder.getOrderNo());
        tb.setCreateTime(new Date());
        tb.setOrderDescribe("已接单");
        //向tb_order_logistics_info中插入一条数据
        tbSenderService.insertStream(tb);
        //如果有物流公司编号则为海外代购，，不需要向tb_sender_order中插入数据
        if("3".equals(state)&&(logisticsCode==null||logisticsCode.equals(""))){
            try {
                //插入tb_sender_order表
                // TODO: 11/22/2016  金鸽
                TbSenderOrder senderOorder = new TbSenderOrder();
                senderOorder.setOrderId(orderId+"");
                //订单到达时间从tb_order中取得，现在写死为当前时间
                senderOorder.setArriveTime(reserveTbOrder.getExtraParam());
                tbSenderService.insertSenderOrder(senderOorder);
                model.addAttribute("senderOorder", senderOorder);
                //推送给店铺下的派送员
                ClientConfig config = ClientConfig.getInstance();
                config.setApnsProduction(false); 	// development env
                config.setTimeToLive(60 * 60 * 24); // one day

                String appKey = Configuration.getInstance().getStringValue("appKey","");
                String masterSecret = Configuration.getInstance().getStringValue("masterSecret","");
                String title = "麻雀加急-";
                String alert = "您有一份新的订单等待派送!";
                Map<String, String> extras = new HashMap<String, String>();
                //查询派送员registration_id
                List<TbSender> list = tbSenderService.selectRegistrationIdbyUserId(UserUtils.getUser().getId());
                List<String> list1 = new ArrayList<String>();
                for(TbSender sender:list){
                    if(!"".equals(sender.getRegistrationId())){
                        list1.add(sender.getRegistrationId());
                    }
                }
                int size = list1.size();
                String[] registrationID = (String[])list1.toArray(new String[size]) ;
                JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, config); 	// JPush client
                jPushClient.sendAndroidNotificationWithRegistrationID(title,alert,extras,registrationID);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return "forward:" + adminPath + "/sys/shoppingOrderProduct/showShoppingOrder/"+reserveTbOrder.getChannelId()+"";
    }

}
